package com.magupe.push.server.handler;

import java.io.File;
import java.io.RandomAccessFile;

import com.magupe.push.common.protocol.request.FileRequestPacket;
import com.magupe.push.common.protocol.response.FileResponsePacket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class FileRequestHandler extends SimpleChannelInboundHandler<FileRequestPacket>{

	private long byteRead;
	
    private volatile Long startPos = 0L;
    
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FileRequestPacket packet) throws Exception {
		FileResponsePacket response = new FileResponsePacket();
		response.setContentId(packet.getContentId());
		response.setSecret(packet.getSecret());
		response.setSuccess(true);
		response.setUserId(packet.getUserId());
		response.setMsgId(packet.getMsgId());
		response.setSource(packet.getSource());
		response.setPath(packet.getPath());
		
		byte[] bytes = packet.getBytes();
		byteRead = packet.getEndPos();
        if (byteRead > 0) {
    		File file = new File("C:/Users/Administrator/Desktop/1568777125606.jpg");
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            randomAccessFile.seek(startPos);
            randomAccessFile.write(bytes);
            randomAccessFile.close();
            startPos = startPos + byteRead;
        	response.setStartPos(startPos);
        } else {
            response.setStartPos(-1);
        }
        
        ctx.channel().writeAndFlush(response);
	}

}
